<?php
App::uses('Sanitize', 'Utility');
class RolesController extends AppController {
	public $name = 'Roles';
	public $components = array('Session', 'Security', 'Auth');
	//public $helpers = array('Cache');


	public function index(){
        $this->set("roles", $this->Role->find('all'));
		$this->set('accessRoles', $accessRoles = array('1' => 'Member', '2' => 'Moderator', '3' => 'Administrator'));
	}

	public function add(){
		if($this->request->is("post")){
			$this->Role->create();
			if($this->Role->save($this->request->data)){
				$this->Session->setFlash("Role created", "default", array("class" => "success"));
				$this->redirect(array("action" => "index"));
			}
		}
	}

	public function edit($id){
		$this->Role->id = $id;
		if(!$this->Role->exists()){
			throw new NotFoundException('Invalid user');
		}

		if($this->request->is("get")){
				$this->request->data = $this->Role->read();
		}else{
			if($this->Role->save($this->request->data)){
				$this->Session->setFlash("Role updated", "default", array("class" => "success"));
				$this->redirect(array("action" => "index"));
			}
		}
	}

	public function delete(){
		if($this->request->is("get")){
			throw new MethodNotAllowedException();
		}elseif($this->request->is("post")){
			$i = 0;
			foreach($this->request->data['Role']['selectedRoles'] AS $roleId){
				$this->Role->id = $roleId;
				$role = $this->Role->read();
				if($role['Role']['user_count'] > 0){
					$cantdelete = true;
				}else{
					$this->Role->delete();
					$i++;
				}

			}

			$msg = $i . ": Roles have been deleted.";
			if($cantdelete){
				$msg .= " Some roles couldn't be deleted as they had users assigned to them, assign these users to another role first.";
			}
			$this->Session->setFlash($msg, "default", array('class' => 'error-message'));

			$this->redirect(array("action" => "index"));
		}
	}


}